<script>
	import Vue from 'vue';
	import WS from '@/plugins/ws.js'
	import NotifiUtil from 'js_sdk/swfq-notification-progress/notification/notification.js'
	import {
		baseurl,
		agrServiceUrl
	} from '@/config/baseUrl.js'
	export default {

		data() {
			return {
				socketTask: null,
				timer: null,
				isForceUpdate: 0,
			}
		},
		onLaunch: function() {
			uni.hideTabBar()
			// #ifdef APP-PLUS
			// plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
			// 	console.log(widgetInfo);
			// 	uni.getSystemInfo({
			// 		success: function(e) {
			// 			console.log(e);
			// 			if (e.platform == 'android') {
			// 				uni.request({
			// 					url: 'http://fishery.ssagroup.cn:9090/base/files/appUpdate',
			// 					data: {
			// 						version: widgetInfo.version,
			// 					},
			// 					complete: (result) => {
			// 						console.log(result.data);
			// 						if (result.data.data === true) {
			// 							uni.showModal({
			// 								title: '发现新版本',
			// 								content: '当前APP有最新版本，请及时更新',
			// 								confirmText: '去浏览器更新',
			// 								success: function(res) {
			// 									if (res.confirm) {
			// 										plus.runtime.openURL(
			// 											'http://fishery.ssagroup.cn:9090/base/files/appDownload'
			// 										)
			// 									} else if (res.cancel) {
			// 										plus.runtime.quit();
			// 									}
			// 								}
			// 							})
			// 						}
			// 					}
			// 				});
			// 			}
			// 		}
			// 	})

			// });
			// #endif
			let that = this
			uni.getSystemInfo({
				success: function(e) {
					Vue.prototype.statusBar = e.statusBarHeight;
					console.log(e);
					// #ifndef MP
					if (e.platform == 'android') {
						Vue.prototype.customBar = e.statusBarHeight + 45;
						Vue.prototype.platform = 'android';
						uni.setStorageSync('clientType', e.platform)
					} else {
						Vue.prototype.customBar = e.statusBarHeight + 45;
						Vue.prototype.platform = 'apple';
						uni.setStorageSync('clientType', e.platform)
					}
					// #endif

					// #ifdef MP-WEIXIN
					let custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.customBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif

					// #ifdef MP-ALIPAY
					Vue.prototype.customBar = e.statusBarHeight + e.titleBarHeight;
					// #endif

					// #ifdef APP-PLUS
					if (e.platform == "android") {
						that.AndroidCheckUpdate();
					}
					// #endif
				}
			});



			// #ifdef APP-PLUS
			// app修改-3.13
			var pinf = plus.push.getClientInfo();
			var cid = pinf.clientid; //客户端标识
			console.log('cid：' + cid);
			uni.setStorageSync('cid', cid);
			if (!cid) {
				setTimeout(() => {
					pinf = plus.push.getClientInfo();
					cid = pinf.clientid; //客户端标识
					console.log('cid：' + cid);
					uni.setStorageSync('cid', cid);
					if (!cid) {
						setTimeout(() => {
							pinf = plus.push.getClientInfo();
							cid = pinf.clientid; //客户端标识
							console.log('cid：' + cid);
							uni.setStorageSync('cid', cid);
							if (!cid) {
								setTimeout(() => {
									pinf = plus.push.getClientInfo();
									cid = pinf.clientid; //客户端标识
									console.log('cid：' + cid);
									uni.setStorageSync('cid', cid);
								}, 1000)
							}
						}, 1000)
					}

				}, 1000)
			}
			// uni.onPushMessage((res) => {
			// 		console.log("收到推送消息：", res) //监听推送消息
			// 	}),
			// 	uni.getPushClientId({
			// 		success: (res) => {
			// 			let cid = res.cid
			// 			uni.setStorageSync('cid', cid);
			// 			console.log('客户端推送标识:', cid)
			// 		},
			// 		fail(err) {
			// 			console.log(err)
			// 		}
			// 	})
			// uni.getSystemInfo({
			// 	success: function(e) {
			// 		if (e.platform == 'android') {
			// 			uni.setStorageSync('clientType', e.platform);
			// 		} else {
			// 			uni.setStorageSync('clientType', e.platform);
			// 		}
			// 	}
			// })
			/* 5+  push 消息推送 ps:使用:H5+的方式监听，实现推送*/
			plus.push.addEventListener(
				'click',
				function(msg) {
					console.log('click:' + JSON.stringify(msg));
					console.log(msg.payload);
					console.log(JSON.stringify(msg));
					if (isIOS) {
						//APP离线点击包含click属性，这时payload是JSON对象
						if (msg.type && msg.type == 'click') {
							payload = msg.payload;
						} else {
							//APP在线，收到消息不会包含type属性,这时的payload是JSON字符串，需要转为JSON对象
							payload = JSON.parse(msg.payload);
						}
						navigateTo(payload);
					} else {
						payload = JSON.parse(msg.payload);
						if (typeof payload === 'string') {
							payload = JSON.parse(payload);
						}
						navigateTo(payload);
					}
				},
				false
			);
			//监听在线消息事件
			plus.push.addEventListener(
				'receive',
				function(msg) {
					// plus.ui.alert(2);
					//这里可以写跳转业务代码
					console.log('recevice:' + JSON.stringify(msg));
					if (!msg.aps && msg.type == 'receive') {
						//创建本地消息,发送的本地消息也会被receive方法接收到，但没有type属性，且aps是null
						plus.push.createMessage(msg.content, JSON.stringify(msg.payload), {
							title: msg.title
						});
					} else {
						//如果是Android，当APP在线时，收到透传消息不会进入系统消息，需要发送本地提醒。
						plus.push.createMessage(msg.content, JSON.stringify(msg.payload), {
							title: msg.title
						});
					}
				},
				false
			);

			// plus.push.addEventListener(
			// 	'click',
			// 	function(msg) {
			// 		console.log("离线推送" + msg)
			// 		uni.navigateTo({
			// 			url: 'pages/pushtest/pushtest'
			// 		});
			// 	},
			// 	false
			// );
			// plus.push.addEventListener(
			// 	'receive',
			// 	function(msg) {
			// 		console.log("在线推送" + msg)
			// 		uni.navigateTo({
			// 			url: 'pages/pushtest/pushtest'
			// 		});
			// 	},
			// 	false
			// );

			// #endif
			// console.log('App Launch')
		},
		onShow: function() {
			// console.log('App Show')
		},
		onUnload() {
			clearTimeout(this.timer)
			this.timer = null
		},
		onHide: function() {
			console.log('App Hide')
			uni.removeStorageSync('personstatus')
		},
		mounted() {
			uni.$on('setupSocket', () => {
				this.setupSocket()
			})
			// 退出登录
			uni.$on('loginOut', () => {
				console.log('loginout');
				this.closeSocket()
			})
			// 用户创建会话
			uni.$on('userCreateNewSession', (res) => {
				clearTimeout(this.timer)
				this.timer = null
				this.userCreateNewSession(res)
			})
		},
		created() {
			if (this.$socketApi === undefined || !this.$socketApi || this.$socketApi === null) {
				this.setupSocket()
			}
		},
		methods: {
			// 关闭socket
			closeSocket() {
				if (this.socketTask != null) {
					this.$socketApi.sendMsg({
						type: -1
					})
					this.socketTask.closeSocket()
				}
			},
			// 初始化
			setupSocket() {
				if (uni.getStorageSync('satoken')) {
					let str = baseurl.split("://")[1]
					const url = `ws://${str}business/webSocket/${uni.getStorageSync('userNo')}`
					
					this.socketTask = new WS(url)
					Vue.prototype.$socketApi = this.socketTask;
				}
			},
			// 重连
			async userCreateNewSession(id) {
				if (!uni.getStorageSync('isExpertFlag')) {
					this.setupSocket()
				}
			},
			AndroidCheckUpdate() {
				let that = this;
				console.log(plus.runtime.appid)
				plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
					that.version = wgtinfo.version //客户端版本号
					console.log('当前app版本信息：' + that.version);
					that.getUpdateVersion()
				})
			},
			getUpdateVersion() {
				let that = this;
				// 获取当前app版本信息
				uni.request({
					url: agrServiceUrl + 'business/version/check?appNo=organization',
					method: 'get',
					success: res => {
						console.log('res.data:' + JSON.stringify(res.data))
						console.log("现在的版本" + that.version + "数据库版本" + res.data.data.versionNo + "进入查找app版本");
						if (res.data.data.versionNo > that.version) {
							let reg = /-/ig;
							let versionNo = res.data.data && res.data.data.versionNo.replace(reg, '');
							// 这里下载apkurl从/appUpdate/queryUpdate接口请求返回数据中获取
							that.downloadUrl = `http://assc.xg1688.com/download/app/xingguangnongfu_b` + '_v' + res.data.data.releaseVersion + '_' + versionNo + '.apk'
							// 是否强制更新（0 否；1 是）
							// that.isForceUpdate = res.data.data.isForceUpdate
							uni.showModal({
								// 更新提醒
								title: '发现新版本，是否更新',
								content: '此版本号：' + that.version + '\xa0\xa0\xa0' + '待更新版本号：' + res.data
									.data.versionNo,
								success: res => {
									if (res.confirm) {
										that.$store.commit('setHide', true)
										that.downWgt(); //下载文件
										// that.showdownLine = true;
										// plus.runtime.openURL(androidUrl)
									} else if (res.cancel) {
										console.log('that.isForceUpdate：' + that.isForceUpdate);
										// 不更新强制退出app
										if (that.isForceUpdate == 1) {
											console.log('that.isForceUpdate1：' + that
												.isForceUpdate);
											uni.showModal({
												// 更新提醒
												title: '发现新版本，是否下载更新',
												content: '此版本为强制更新版本如不升级将退出APP',
												confirmText: '退出',
												success: res => {
													if (res.confirm) {
														console.log('不更新强制退出app');
														plus.runtime.quit();
													} else if (res.cancel) {
														that.AndroidCheckUpdate();
													}
												}
											});
										}
									}
								}
							});
							//downloadTask.start();   
						}
					}
				});
				complete: () => {}
			},
			downWgt() {
				let that = this;
				that.$store.commit('setHide', true)
				// this.Version.downloadApkAndShowProgressForUpdate(that.downloadUrl)
				const downloadTask = uni.downloadFile({ //执行下载
					url: that.downloadUrl, //下载地址
					timeout: 1000 * 30, //30秒超时时间
					success: downloadResult => { //下载成功
						that.showdownLine = false
						// uni.hideLoading();
						console.log('downloadResult.statusCode' + downloadResult.statusCode)
						if (downloadResult.statusCode == 200) {

							that.$store.commit('setHide', false)
							console.log('下载中')
							uni.showModal({
								title: '',
								content: '下载成功，确定现在安装吗？',
								confirmText: '安装',
								confirmColor: '#EE8F57',
								success: function(res) {
									if (res.confirm == true) {
										plus.runtime.install( // 安装
											downloadResult.tempFilePath, {
												force: true
											},
											function(res) {
												utils.showToast('下载成功，请手动安装');
												plus.runtime.restart();
											}
										);
									} else if (res.cancel) {
										// that.AndroidCheckUpdate();
										// console.log('不更新强制退出app');
										// plus.runtime.quit();
									}
								}
							});
						}
					},
					fail: err => {
						uni.hideLoading();
						that.showdownLine = false
						that.$u.toast(err.errMsg)
						console.log(err)
					},
					complete: com => {
						console.log(com)
					}
				});

				var appname = '';
				var NotificationUtil = NotifiUtil(); //实例创建
				NotificationUtil.setNotification(appname, "开始下载! ");
				// 下载进度
				downloadTask.onProgressUpdate(res => {
					// that.$u.toast(res.progress)
					// console.log(res)
					// let current = parseInt(res.downloadedSize / task.totalSize * 100)
					// console.log('下载进度' + that.downloadNum);
					// 更新下载进度
					that.$store.commit('setRogress', res.progress)
					that.downloadNum = res.progress

					// #ifdef APP-PLUS
					// plus.push.createMessage(res.progress + '%', JSON.stringify(''), {
					// 	title: '下载中......'
					// });
					// plus.push.clear() 

					if (res.progress === 100) {
						// console.log("Download success: " + task.filename);
						NotificationUtil.compProgressNotification(appname, "下载完成! ");
					} else {
						NotificationUtil.setProgress(res.progress, '');
					}
					// #endif
					// console.log('已经下载的数据长度' + res.totalBytesWritten);
					// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);

					// 满足测试条件，取消下载任务。
					// if (res.progress > 50) {
					// 	downloadTask.abort();
					// }
				});

				// uni.showLoading({
				// 	title: that.downloadNum + '%'
				// })
			},
		}
	};
</script>

<style lang="scss">
	/* #ifndef APP-PLUS-NVUE */
	@import '@/style/common.scss';
	@import url('@/common/icon/iconfont.css');

	uni-page-wrapper {
		width: 100%;
		heigth: 100%;
	}

	uni-page-body,
	page {
		width: 100%;
		height: 100%;
		overflow: hidden;
	}

	/* #endif */
</style>